import { useRequest } from 'ahooks';
import { Button, Form, Input } from 'antd';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';

import { loginProxy } from '@/store/userStore';
import messageBox from '@/utils/messageBox';

import styles from '../index.module.scss';
import { login, LoginProps } from '../service';

const Login = () => {
  const navigate = useNavigate();
  const { t } = useTranslation() as { t: (a: string) => string };
  const [form] = Form.useForm();

  const { run: runLogin, loading } = useRequest(
    async (params: LoginProps = form.getFieldsValue()) => {
      await login(params).then(res => {
        const { token, username, avatar, background } = res.data;
        loginProxy({ token, username, avatar, background });
        messageBox.success({ content: `Welcome ${username}` });
        navigate('/');
      });
    },
    { manual: true },
  );

  return (
    <div className={styles.loginCard}>
      <h1 className="text-3xl font-bold mb-14 sm:mb-0">{t('signIn')}</h1>
      <Form form={form} onFinish={runLogin}>
        <Form.Item name="username" rules={[{ required: true, message: t('usernameRequire') }]}>
          <Input placeholder={t('usernamePlaceholder')} className="w-72 h-10" />
        </Form.Item>
        <Form.Item name="password" rules={[{ required: true, message: t('passwordRequire') }]}>
          <Input.Password
            onPressEnter={() => runLogin()}
            placeholder={t('passwordPlaceholder')}
            className="w-72 h-10"
          />
        </Form.Item>
      </Form>
      <Button className="submitBtn" loading={loading} onClick={() => form.submit()}>
        {t('SIGNIN')}
      </Button>
    </div>
  );
};

export default Login;
